<template>
  <div class="ai-tags-panel">
    <!-- 面板头部 -->
    <div class="panel-header">
      <div class="header-title">
        <tiny-icon-tag />
        <span>AI智能标签</span>
      </div>
      <div class="header-actions">
        <button
          v-if="selectedFiles.length > 0"
          :disabled="selectedFiles.length === 0 || isProcessing"
          class="action-btn"
          @click="recognizeSelectedFiles"
        >
          <tiny-loading v-if="isProcessing" size="small" />
          <tiny-icon-magic v-else />
          {{ isProcessing ? '识别中...' : 'AI识别' }}
        </button>
        <button class="action-btn" @click="togglePanel">
          <tiny-icon-chevron-up v-if="isExpanded" />
          <tiny-icon-chevron-down v-else />
        </button>
      </div>
    </div>

    <!-- 面板内容 -->
    <div v-show="isExpanded" class="panel-content">
      <!-- 快速操作 -->
      <div class="quick-actions">
        <button
          class="quick-btn"
          @click="showRecommendedTags"
        >
          <tiny-icon-lightbulb />
          推荐标签
        </button>
        <button
          class="quick-btn"
          @click="showPopularTags"
        >
          <tiny-icon-fire />
          热门标签
        </button>
        <button
          :disabled="selectedFiles.length === 0"
          class="quick-btn"
          @click="smartClassify"
        >
          <tiny-icon-folder />
          智能分类
        </button>
        <button
          :disabled="selectedFiles.length !== 1"
          class="quick-btn"
          @click="detectSimilar"
        >
          <tiny-icon-copy />
          相似检测
        </button>
      </div>

      <!-- 处理进度 -->
      <div v-if="processingTasksCount > 0" class="processing-status">
        <div class="status-header">
          <span>正在处理 {{ processingTasksCount }} 个文件</span>
          <span class="progress-text">{{ processingProgress }}%</span>
        </div>
        <div class="progress-bar">
          <div
            :style="{ width: processingProgress + '%' }"
            class="progress-fill"
          ></div>
        </div>
        <div class="processing-files">
          <div
            v-for="task in activeTasks"
            :key="task.id"
            class="processing-file"
          >
            <div class="file-info">
              <span class="file-name">{{ task.fileName }}</span>
              <span :class="task.status" class="file-status">
                {{ getStatusText(task.status) }}
              </span>
            </div>
            <tiny-loading v-if="task.status === 'processing'" size="small" />
            <tiny-icon-check v-else-if="task.status === 'completed'" class="success-icon" />
            <tiny-icon-close v-else-if="task.status === 'failed'" class="error-icon" />
          </div>
        </div>
      </div>

      <!-- 最近识别结果 -->
      <div v-if="recentResults.length > 0" class="recent-results">
        <h4>最近识别结果</h4>
        <div class="results-list">
          <div
            v-for="result in recentResults.slice(0, 5)"
            :key="result.fileId"
            class="result-item"
            @click="viewResultDetail(result)"
          >
            <div class="result-info">
              <div class="result-meta">
                <span class="file-id">#{{ result.fileId }}</span>
                <span class="processing-time">{{ result.processingTime }}ms</span>
              </div>
              <div class="result-tags">
                <span
                  v-for="tag in (result.tags || []).slice(0, 3)"
                  :key="tag.name"
                  :style="{ opacity: tag.confidence || 1 }"
                  class="result-tag"
                >
                  {{ tag.name }}
                </span>
                <span v-if="(result.tags || []).length > 3" class="more-tags">
                  +{{ (result.tags || []).length - 3 }}
                </span>
              </div>
            </div>
            <div class="result-score">
              <tiny-icon-star />
              {{ Math.round((result.qualityScore || 0) * 100) }}%
            </div>
          </div>
        </div>
      </div>

      <!-- 标签统计 -->
      <div class="tags-statistics">
        <h4>标签统计</h4>
        <div class="stats-grid">
          <div class="stat-item">
            <div class="stat-number">{{ statistics.totalProcessed || 0 }}</div>
            <div class="stat-label">已处理文件</div>
          </div>
          <div class="stat-item">
            <div class="stat-number">{{ statistics.tagsGenerated || 0 }}</div>
            <div class="stat-label">生成标签</div>
          </div>
          <div class="stat-item">
            <div class="stat-number">{{ Math.round((statistics.accuracyRate || 0) * 100) }}%</div>
            <div class="stat-label">识别准确率</div>
          </div>
        </div>
      </div>

      <!-- 配置选项 -->
      <div class="ai-config">
        <h4>处理配置</h4>
        <div class="config-options">
          <tiny-checkbox
            v-model="localConfig.autoRecognition"
            @change="updateConfig"
          >
            自动识别新上传文件
          </tiny-checkbox>
          <tiny-checkbox
            v-model="localConfig.enableFaceRecognition"
            @change="updateConfig"
          >
            启用人脸识别
          </tiny-checkbox>
          <tiny-checkbox
            v-model="localConfig.enableObjectDetection"
            @change="updateConfig"
          >
            启用物体检测
          </tiny-checkbox>
          <tiny-checkbox
            v-model="localConfig.enableSafetyCheck"
            @change="updateConfig"
          >
            内容安全检测
          </tiny-checkbox>
        </div>

        <div class="config-sliders">
          <div class="slider-item">
            <label>置信度阈值: {{ localConfig.confidenceThreshold }}</label>
            <tiny-slider
              v-model="localConfig.confidenceThreshold"
              :max="1"
              :min="0.1"
              :step="0.1"
              @change="updateConfig"
            />
          </div>
          <div class="slider-item">
            <label>最大标签数: {{ localConfig.maxTags }}</label>
            <tiny-slider
              v-model="localConfig.maxTags"
              :max="20"
              :min="3"
              :step="1"
              @change="updateConfig"
            />
          </div>
        </div>
      </div>
    </div>

    <!-- 标签详情对话框 -->
    <tiny-dialog
      v-model="resultDetailVisible"
      class="result-detail-dialog"
      title="AI识别详情"
      width="800px"
    >
      <div v-if="selectedResult" class="result-detail">
        <div class="detail-overview">
          <div class="overview-item">
            <span class="label">文件ID:</span>
            <span class="value">#{{ selectedResult.fileId }}</span>
          </div>
          <div class="overview-item">
            <span class="label">处理时间:</span>
            <span class="value">{{ selectedResult.processingTime }}ms</span>
          </div>
          <div class="overview-item">
            <span class="label">质量评分:</span>
            <span class="value">{{ Math.round((selectedResult.qualityScore || 0) * 100) }}%</span>
          </div>
          <div class="overview-item">
            <span class="label">安全评分:</span>
            <span class="value">{{ Math.round((selectedResult.safetyScore || 0) * 100) }}%</span>
          </div>
        </div>

        <div class="detail-sections">
          <!-- 标签详情 -->
          <div v-if="selectedResult.tags?.length" class="detail-section">
            <h4>识别标签</h4>
            <div class="tags-detail">
              <div
                v-for="tag in selectedResult.tags"
                :key="tag.name"
                class="tag-detail-item"
              >
                <span class="tag-name">{{ tag.name }}</span>
                <span class="tag-category">{{ tag.category }}</span>
                <span class="tag-confidence">{{ Math.round((tag.confidence || 0) * 100) }}%</span>
              </div>
            </div>
          </div>

          <!-- 检测对象 -->
          <div v-if="selectedResult.objects?.length" class="detail-section">
            <h4>检测对象</h4>
            <div class="objects-detail">
              <div
                v-for="obj in selectedResult.objects"
                :key="obj.name"
                class="object-item"
              >
                <span class="object-name">{{ obj.name }}</span>
                <span class="object-confidence">{{ Math.round((obj.confidence || 0) * 100) }}%</span>
              </div>
            </div>
          </div>

          <!-- 场景识别 -->
          <div v-if="selectedResult.scenes?.length" class="detail-section">
            <h4>场景识别</h4>
            <div class="scenes-detail">
              <span
                v-for="scene in selectedResult.scenes"
                :key="scene.name"
                class="scene-tag"
              >
                {{ scene.name }} ({{ Math.round((scene.confidence || 0) * 100) }}%)
              </span>
            </div>
          </div>

          <!-- 推荐相册 -->
          <div v-if="selectedResult.recommendedAlbums?.length" class="detail-section">
            <h4>推荐相册</h4>
            <div class="recommended-albums">
              <span
                v-for="album in selectedResult.recommendedAlbums"
                :key="album"
                class="album-tag"
              >
                {{ album }}
              </span>
            </div>
          </div>

          <!-- 主要颜色 -->
          <div v-if="selectedResult.dominantColors?.length" class="detail-section">
            <h4>主要颜色</h4>
            <div class="colors-detail">
              <div
                v-for="color in selectedResult.dominantColors"
                :key="color.hex"
                class="color-item"
              >
                <div
                  :style="{ backgroundColor: color.hex }"
                  class="color-swatch"
                ></div>
                <span class="color-name">{{ color.colorName }}</span>
                <span class="color-percentage">{{ Math.round(color.percentage) }}%</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </tiny-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, watch, onMounted } from 'vue'
import { TinyMessage as Message } from '@opentiny/vue'
import { useAiStore } from '@/stores/ai'
import { smartClassifyFiles, detectSimilarFiles } from '@/api/ai'

// Props
interface Props {
  selectedFiles: any[]
  visible?: boolean
}

const props = withDefaults(defineProps<Props>(), {
  visible: true
})

// Emits
const emit = defineEmits<{
  classify: [albums: string[]]
  similarFiles: [files: any[]]
  tagSelected: [tag: string]
}>()

// Store
const aiStore = useAiStore()

// 响应式数据
const isExpanded = ref(props.visible)
const resultDetailVisible = ref(false)
const selectedResult = ref<any>(null)

// 本地配置副本
const localConfig = reactive({
  autoRecognition: true,
  confidenceThreshold: 0.7,
  maxTags: 10,
  enableFaceRecognition: true,
  enableObjectDetection: true,
  enableSceneRecognition: true,
  enableOCR: false,
  enableColorAnalysis: true,
  enableSafetyCheck: true
})

// 计算属性
const isProcessing = computed(() => aiStore.isProcessing)
const processingTasksCount = computed(() => aiStore.processingTasksCount)
const processingProgress = computed(() => aiStore.processingProgress)
const recentResults = computed(() => aiStore.recentResults)
const statistics = computed(() => aiStore.statistics)

const activeTasks = computed(() =>
  aiStore.processingTasks.filter(task =>
    task.status === 'processing' || task.status === 'pending'
  ).slice(0, 3)
)

// 方法
const togglePanel = () => {
  isExpanded.value = !isExpanded.value
}

const recognizeSelectedFiles = async () => {
  if (props.selectedFiles.length === 0) {
    Message.warning('请先选择要识别的文件')
    return
  }

  try {
    const files = props.selectedFiles.map(file => ({
      fileId: file.fileId,
      fileName: file.fileName
    }))

    await aiStore.batchRecognizeFiles(files)
    Message.success('AI识别任务已开始')
  } catch (error) {
    console.error('AI识别失败:', error)
    Message.error('AI识别失败')
  }
}

const showRecommendedTags = async () => {
  await aiStore.loadRecommendedTags()
  Message.info('推荐标签已更新')
}

const showPopularTags = async () => {
  await aiStore.loadPopularTags()
  Message.info('热门标签已更新')
}

const smartClassify = async () => {
  if (props.selectedFiles.length === 0) {
    Message.warning('请先选择要分类的文件')
    return
  }

  try {
    const fileIds = props.selectedFiles.map(file => file.fileId)
    const response = await smartClassifyFiles(fileIds)

    if (response.code === 200) {
      emit('classify', response.data)
      Message.success('智能分类完成')
    }
  } catch (error) {
    console.error('智能分类失败:', error)
    Message.error('智能分类失败')
  }
}

const detectSimilar = async () => {
  if (props.selectedFiles.length !== 1) {
    Message.warning('请选择一个文件进行相似检测')
    return
  }

  try {
    const fileId = props.selectedFiles[0].fileId
    const response = await detectSimilarFiles(fileId)

    if (response.code === 200) {
      emit('similarFiles', response.data)
      Message.success(`发现 ${response.data.length} 个相似文件`)
    }
  } catch (error) {
    console.error('相似检测失败:', error)
    Message.error('相似检测失败')
  }
}

const viewResultDetail = (result: any) => {
  selectedResult.value = result
  resultDetailVisible.value = true
}

const updateConfig = () => {
  aiStore.updateProcessingConfig(localConfig)
}

const getStatusText = (status: string) => {
  const statusMap = {
    pending: '等待中',
    processing: '处理中',
    completed: '已完成',
    failed: '失败'
  }
  return statusMap[status] || status
}

// 初始化配置
watch(() => aiStore.processingConfig, (newConfig) => {
  Object.assign(localConfig, newConfig)
}, { immediate: true })

// 页面加载时获取数据
onMounted(() => {
  aiStore.loadStatistics()
  aiStore.loadPopularTags()
  aiStore.loadRecommendedTags()
})
</script>

<style lang="scss" scoped>
.ai-tags-panel {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: $radius-lg;
  border: 1px solid rgba(255, 255, 255, 0.2);
  overflow: hidden;
  transition: all $duration-normal ease;

  .panel-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: $spacing-4;
    background: rgba(255, 255, 255, 0.1);
    border-bottom: 1px solid rgba(255, 255, 255, 0.1);

    .header-title {
      display: flex;
      align-items: center;
      gap: $spacing-2;
      font-weight: $font-weight-semibold;
      color: $gray-800;
    }

    .header-actions {
      display: flex;
      align-items: center;
      gap: $spacing-2;

      .action-btn {
        display: flex;
        align-items: center;
        gap: $spacing-1;
        padding: $spacing-1 $spacing-3;
        background: transparent;
        border: 1px solid rgba($primary-500, 0.3);
        border-radius: $radius-md;
        color: $primary-600;
        font-size: $font-size-sm;
        cursor: pointer;
        transition: all $duration-fast ease;

        &:hover:not(:disabled) {
          background: rgba($primary-500, 0.1);
          border-color: $primary-500;
        }

        &:disabled {
          opacity: 0.5;
          cursor: not-allowed;
        }
      }
    }
  }

  .panel-content {
    padding: $spacing-4;

    .quick-actions {
      display: flex;
      flex-wrap: wrap;
      gap: $spacing-2;
      margin-bottom: $spacing-4;

      .quick-btn {
        display: flex;
        align-items: center;
        gap: $spacing-1;
        padding: $spacing-2 $spacing-3;
        background: rgba($secondary-500, 0.1);
        border: none;
        border-radius: $radius-md;
        color: $secondary-600;
        font-size: $font-size-sm;
        cursor: pointer;
        transition: all $duration-fast ease;

        &:hover:not(:disabled) {
          background: rgba($secondary-500, 0.2);
          transform: translateY(-1px);
        }

        &:disabled {
          opacity: 0.5;
          cursor: not-allowed;
        }
      }
    }

    .processing-status {
      margin-bottom: $spacing-4;
      padding: $spacing-3;
      background: rgba($info, 0.1);
      border-radius: $radius-md;
      border: 1px solid rgba($info, 0.2);

      .status-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: $spacing-2;
        font-size: $font-size-sm;
        font-weight: $font-weight-medium;
        color: $info;
      }

      .progress-bar {
        height: 4px;
        background: rgba($info, 0.2);
        border-radius: $radius-full;
        overflow: hidden;
        margin-bottom: $spacing-3;

        .progress-fill {
          height: 100%;
          background: $info;
          transition: width $duration-normal ease;
        }
      }

      .processing-files {
        display: flex;
        flex-direction: column;
        gap: $spacing-2;

        .processing-file {
          display: flex;
          align-items: center;
          justify-content: space-between;
          padding: $spacing-2;
          background: rgba(255, 255, 255, 0.5);
          border-radius: $radius-sm;

          .file-info {
            display: flex;
            flex-direction: column;
            gap: 2px;

            .file-name {
              font-size: $font-size-sm;
              font-weight: $font-weight-medium;
              color: $gray-700;
            }

            .file-status {
              font-size: $font-size-xs;

              &.processing { color: $info; }
              &.completed { color: $success; }
              &.failed { color: $error; }
            }
          }

          .success-icon { color: $success; }
          .error-icon { color: $error; }
        }
      }
    }

    .recent-results {
      margin-bottom: $spacing-4;

      h4 {
        font-size: $font-size-md;
        font-weight: $font-weight-semibold;
        color: $gray-800;
        margin-bottom: $spacing-3;
      }

      .results-list {
        display: flex;
        flex-direction: column;
        gap: $spacing-2;

        .result-item {
          display: flex;
          align-items: center;
          justify-content: space-between;
          padding: $spacing-3;
          background: rgba(255, 255, 255, 0.3);
          border-radius: $radius-md;
          cursor: pointer;
          transition: all $duration-fast ease;

          &:hover {
            background: rgba(255, 255, 255, 0.5);
            transform: translateX(4px);
          }

          .result-info {
            flex: 1;

            .result-meta {
              display: flex;
              gap: $spacing-2;
              margin-bottom: $spacing-1;
              font-size: $font-size-xs;
              color: $gray-500;
            }

            .result-tags {
              display: flex;
              flex-wrap: wrap;
              gap: $spacing-1;

              .result-tag {
                padding: 2px $spacing-2;
                background: rgba($primary-500, 0.1);
                color: $primary-600;
                border-radius: $radius-sm;
                font-size: $font-size-xs;
              }

              .more-tags {
                padding: 2px $spacing-2;
                background: rgba($gray-500, 0.1);
                color: $gray-600;
                border-radius: $radius-sm;
                font-size: $font-size-xs;
              }
            }
          }

          .result-score {
            display: flex;
            align-items: center;
            gap: 4px;
            color: $warning;
            font-size: $font-size-sm;
            font-weight: $font-weight-medium;
          }
        }
      }
    }

    .tags-statistics {
      margin-bottom: $spacing-4;

      h4 {
        font-size: $font-size-md;
        font-weight: $font-weight-semibold;
        color: $gray-800;
        margin-bottom: $spacing-3;
      }

      .stats-grid {
        display: grid;
        grid-template-columns: repeat(3, 1fr);
        gap: $spacing-3;

        .stat-item {
          text-align: center;
          padding: $spacing-3;
          background: rgba(255, 255, 255, 0.3);
          border-radius: $radius-md;

          .stat-number {
            font-size: $font-size-lg;
            font-weight: $font-weight-bold;
            color: $primary-500;
            margin-bottom: $spacing-1;
          }

          .stat-label {
            font-size: $font-size-xs;
            color: $gray-600;
          }
        }
      }
    }

    .ai-config {
      h4 {
        font-size: $font-size-md;
        font-weight: $font-weight-semibold;
        color: $gray-800;
        margin-bottom: $spacing-3;
      }

      .config-options {
        display: flex;
        flex-direction: column;
        gap: $spacing-2;
        margin-bottom: $spacing-4;
      }

      .config-sliders {
        display: flex;
        flex-direction: column;
        gap: $spacing-3;

        .slider-item {
          label {
            display: block;
            margin-bottom: $spacing-2;
            font-size: $font-size-sm;
            font-weight: $font-weight-medium;
            color: $gray-700;
          }
        }
      }
    }
  }
}

// 对话框样式
.result-detail-dialog {
  .result-detail {
    .detail-overview {
      display: grid;
      grid-template-columns: repeat(2, 1fr);
      gap: $spacing-3;
      margin-bottom: $spacing-6;
      padding-bottom: $spacing-4;
      border-bottom: 1px solid rgba(255, 255, 255, 0.1);

      .overview-item {
        display: flex;
        justify-content: space-between;
        align-items: center;

        .label {
          font-weight: $font-weight-medium;
          color: $gray-600;
        }

        .value {
          font-weight: $font-weight-semibold;
          color: $gray-800;
        }
      }
    }

    .detail-sections {
      display: flex;
      flex-direction: column;
      gap: $spacing-4;

      .detail-section {
        h4 {
          font-size: $font-size-md;
          font-weight: $font-weight-semibold;
          color: $gray-800;
          margin-bottom: $spacing-3;
        }

        .tags-detail {
          display: flex;
          flex-direction: column;
          gap: $spacing-2;

          .tag-detail-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: $spacing-2 $spacing-3;
            background: rgba(255, 255, 255, 0.3);
            border-radius: $radius-md;

            .tag-name {
              font-weight: $font-weight-medium;
            }

            .tag-category {
              color: $gray-500;
              font-size: $font-size-sm;
            }

            .tag-confidence {
              color: $primary-500;
              font-weight: $font-weight-semibold;
            }
          }
        }

        .objects-detail {
          display: flex;
          flex-wrap: wrap;
          gap: $spacing-2;

          .object-item {
            display: flex;
            gap: $spacing-2;
            padding: $spacing-2 $spacing-3;
            background: rgba($info, 0.1);
            border-radius: $radius-md;
            font-size: $font-size-sm;

            .object-confidence {
              color: $info;
              font-weight: $font-weight-medium;
            }
          }
        }

        .scenes-detail,
        .recommended-albums {
          display: flex;
          flex-wrap: wrap;
          gap: $spacing-2;

          .scene-tag,
          .album-tag {
            padding: $spacing-2 $spacing-3;
            background: rgba($secondary-500, 0.1);
            color: $secondary-600;
            border-radius: $radius-md;
            font-size: $font-size-sm;
          }
        }

        .colors-detail {
          display: flex;
          flex-wrap: wrap;
          gap: $spacing-3;

          .color-item {
            display: flex;
            align-items: center;
            gap: $spacing-2;

            .color-swatch {
              width: 24px;
              height: 24px;
              border-radius: $radius-sm;
              border: 1px solid rgba(0, 0, 0, 0.1);
            }

            .color-name {
              font-size: $font-size-sm;
            }

            .color-percentage {
              font-size: $font-size-xs;
              color: $gray-500;
            }
          }
        }
      }
    }
  }
}

// 暗色主题
[data-theme="dark"] {
  .ai-tags-panel {
    background: rgba(0, 0, 0, 0.8);
    border-color: rgba(255, 255, 255, 0.1);

    .panel-header {
      background: rgba(255, 255, 255, 0.05);

      .header-title {
        color: $gray-200;
      }
    }

    .panel-content {
      h4 {
        color: $gray-200;
      }

      .result-item {
        background: rgba(255, 255, 255, 0.05);

        &:hover {
          background: rgba(255, 255, 255, 0.1);
        }
      }
    }
  }
}
</style>
